package com.medranocg.gd.filters

import org.apache.commons.logging.LogFactory

import com.medranocg.gd.alfresco.AlfrescoServiceConnection
import com.medranocg.gd.alfresco.Utils
import com.medranocg.gd.RBAC

class SecurityFilters {
    
    static final log = LogFactory.getLog(this)
    def grailsApplication

    def filters = {
        all(controller:'*', action:'*') {
            before = {
                
                if (session.usuario != null) {
                    log.info("usuario is already in session: ${session.usuario.getUserName()}")
                    return true
                } 

                def userName = request.getRemoteUser()
                def rbac = RBAC.getInstance(session, userName)
				session.rbac = rbac

                def usuario = rbac.getUsuario()               
                addUserToAlfrescoGroups(rbac) 
                session.usuario = usuario
                return true

            }
            after = { Map model ->

            }
            afterView = { Exception e ->

            }
        }
    }

    private def addUserToAlfrescoGroups(rbac) {

        def usuario = rbac.getUsuario()
        def actingAsUser = grailsApplication.config.alfresco.credentials.user
        def alfClient = new Utils(grailsApplication.config.alfresco)
                                .getClient(loggedInUser: actingAsUser)

        def addUserToGroup = { userName, groupName -> 
            def result = alfClient.addUserToGroup(userName, groupName)
            if (result.success) {
                log.info "User '${userName}' was added successfully to '${groupName}'"
                return true
            } else {
                log.error "User '${userName}' could not be added to group '${groupName}': ${result.message}"
                if (result.data) {
                    log.error result.data
                }
                return false
            }

        }

        rbac.roles().each { role -> 
            def groupName = grailsApplication.config.alfresco.roleMap[role]
            def userName = usuario.getUserName()
            log.info "Adding user '${userName}' to '${groupName}' (role: ${role}) as '${actingAsUser}'"
            addUserToGroup(userName, groupName)
        }
    
    }

}
